import json
import random
import time
from urllib import request
from bs4 import BeautifulSoup

import mysql.connector
from fdfs_client.client import get_tracker_conf, Fdfs_client

def initMysql():
  global mydb
  global mycursor
  # mydb = mysql.connector.connect(
  #   host='8.129.219.66',
  #   user='guifangtong',
  #   passwd='guifangtong1234!@#',
  #   database='guifangtong'
  # )

  mydb = mysql.connector.connect(
    host='localhost',
    user='root',
    passwd='root1234',
    database='guifangtong'
  )
  mycursor = mydb.cursor()


def addFangs(fang):
  # initMysql()
  table_name = 't_fang'
  # sql = "INSERT INTO " + table_name + " (name,creat_time,update_time,deleted,des,type_id,attach) VALUES (%s, %s, %s, %s, %s, %s, %s)"
  sql = "INSERT INTO " + table_name + "(create_time,deleted,name,price,price_detail,property,open_date,location,area,build_address,lng_lat," \
                                      "sale_address,traffic,hospital,market,school,special,real_pics,area_pic,status,estate_type," \
                                      "fix_type,build_type,feature,block_count,for_sale_block,for_sale_layout,site_area,floor_area," \
                                      "planned_households,parking_lot_rat,green_rat,floor_area_rat,main_layout,build_com,estate_com,estate_fee,deliver_date,content,show_index) " \
                                      " VALUES "
  # " VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  # print(sql)
  # valsql = '(' + fang['name']+ fang['price']+ fang['priceDetail']+fang['property']+ fang['openDate']+ fang['location']+ \
  #          fang['area'], fang['buildAddress'], fang['lngLat'], fang['saleAddress'] + fang['traffic'] + fang['hospital'] + fang['market'] + fang['school'] + fang['special'] + fang['realPics'] + \
  # fang['areaPic'] + fang['status'] + fang['estateType'] + fang['fixType'] + fang['buildType'] + fang['feature'] + fang['blockCount']+\
  #          fang['forSaleBlock'] + fang['forSaleLayout'] + fang['siteArea'] + fang['floorArea'] + fang['plannedHouseholds'] + fang['parkingLotRat'] + fang['greenRat'] + fang['floorAreaRat'] + fang['mainLayout']+\
  # fang['buildCom'] + fang['estateCom'] + fang['estateFee'] + fang['deliverDate'] + fang['content'] + fang['showIndex'] + ')'
  valsql = '("' + fang['creat_time'] + '",0,"' + fang['name'] + '",' + fang['price'] + ',"' + fang[
    'priceDetail'] + '",' + fang['property'] + ',"' + fang['openDate'] + '","' + fang['location'] + '",' + \
           fang['area'] + ',"' + fang['buildAddress'] + '","' + fang['lngLat'] + '","' + fang['saleAddress'] + '","' + \
           fang['traffic'] + '","' + fang['hospital'] + '","' + \
           fang['market'] + '","' + fang['school'] + '","' + fang['special'] + '","' + fang['realPics'] + '","' + fang[
             'areaPic'] + '",' + fang['status'] + ',' + \
           fang['estateType'] + ',' + fang['fixType'] + ',' + fang['buildType'] + ',"' + fang['feature'] + '","' + fang[
             'blockCount'] + '","' + fang['forSaleBlock'] + '","' + \
           fang['forSaleLayout'] + '","' + fang['siteArea'] + '","' + fang['floorArea'] + '","' + fang[
             'plannedHouseholds'] + '","' + fang['parkingLotRat'] + '","' + \
           fang['greenRat'] + '","' + fang['floorAreaRat'] + '","' + fang['mainLayout'] + '","' + fang[
             'buildCom'] + '","' + fang['estateCom'] + '","' + fang['estateFee'] + '","' + \
           fang['deliverDate'] + '","' + fang['content'] + '",' + fang['showIndex']+');'
  # print(sql + valsql)
  f = "./sql/page_index_"+str(page_index)+"_hengfangbao.sql"
  with open(f,"a",encoding="utf-8") as file:
    file.write(sql + valsql+'\n')
    file.close()
    # mycursor.execute(sql, valsql)
  # mydb.commit()


def uploadPic(picurl):
  try:
    tracker_path = get_tracker_conf('./client.conf')
    client = Fdfs_client(tracker_path)
    # ret_upload
    # ret_upload = client.upload_by_filename('D://12.jpg') # 图片地址
    resp = request.urlopen(picurl)
    # image = np.asarray(bytearray(resp.read()), dtype="uint8")
    ret_upload = client.upload_by_buffer(resp.read())  # 图片地址
    # print(ret_upload['Remote file_id'])
    # print(ret_upload)
    return ret_upload['Remote file_id']
  except Exception as e:
    print('连接失败', e)


builds = ['南宁市龙光玖骏房地产开发有限公司', '南宁市耀辉房地产开发有限公司', '南宁市汉军房地产开发有限责任公司', '南宁市盈顺科技有限公司']
esteComs = ['龙光物业', '广东龙光集团物业管理有限公司南宁分公司', '深圳市深华物业集团有限公司南宁第一分公司', '世邦魏理仕']


def sousuoLgb():
  global page_index
  page_index = 3
  # url = 'https://lgbao.logan.com.cn/olshow/v1/web/product/estate/query/recommend?city=450100&province=450000&recommendData=1'
  url = 'https://hfb.hengfangbao.cn/api/public/houses?page='+str(page_index)+'&pageSize=100'
  # 直接请求
  response = request.urlopen(url)
  # 获取状态码，如果是200表示成功
  # print(response.status)
  # 读取网页内容
  context = response.read().decode('utf-8')
  data = json.loads(context)
  result = data['result']
  print('条数：---' + str(len(result['items'])))
  # print(data['data'])
  for item in result['items']:
    picurl = uploadPic(item['thumb'])
    picurl = picurl.decode('utf-8')
    k = random.randint(1, 11)
    kk = random.randint(0, 9)
    kkk = random.randint(1, 2)
    bk = random.randint(0, 3)
    creat_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    if item['average_price'] == '待定':
        item['average_price'] = 20000

    fangObj = {
      # 第一排
      'name': item['name'],
      'creat_time': creat_time,
      'price': str(item['average_price']),
      'priceDetail': '均价' + str(item['average_price']) + '-' + str(k + item['average_price']) + '（毛坯）',
      'property': str(70),
      'openDate': creat_time,
      'location': str(item['county_name']),
      'area': '1',
      'buildAddress': str(item['county_name']),
      'lngLat': '22.835004,108.360923',
      'saleAddress': str(item['county_name']),

      # 第二排
      'traffic': ' 公交：15、26、56、702路，五象小学站，49、107路，龙堤五象路口站，12路，五象大桥南站；地铁：地铁4号线玉象站（在建）',
      'hospital': ' 广西国际壮医医院、江滨医院、工人医院、医科大一附院；',
      'market': ' 五象航洋城、梦之岛、威宁邻家广场、宜家；',
      'school': ' 幼儿园：大观天下幼儿园，多元新兴实验幼儿园，良庆区第三实验幼儿园；中小学：五象小学，龙堤中学；大学：广西医科大学',
      'special': '11,' + str(k),
      'realPics': picurl + '|group1/M00/00/00/rBOXs1-qZGSADnn7AA2hdWnaXM0418.png|group1/M00/00/00/rBOXs1-qZGSAf5uXAA2EG2Suxr8397.png|group1/M00/00/00/rBOXs1-qZGSAZoq-ABNzPKl0Kbc236.png',
      'areaPic': picurl, #错了
      'status': str(kkk),
      'estateType': str(kk),
      'fixType': str(kkk),
      'buildType': str(kkk),
      'feature': str(item['id']),
      'blockCount': '共8栋，1栋3层商业，1栋' + str(k) + '层酒店，2栋' + str(k) + '-10层小高层，3栋15-' + str(
        item['get_count'] + 25) + '高层，1栋' + str(item['get_count'] + 30) + '层超高层。',

      # 第三排
      # 'forSaleBlock': str(item['houseHolds']),
      'forSaleBlock': '1栋' + str((k + 1)) + '层商业，1栋' + str(k) + '层酒店，2栋5-' + str(int(item['get_count']) + 10) + '层小高层',
      'forSaleLayout': str(int(item['get_count'])),
      'siteArea': str(item['get_count'] * 5),
      'floorArea': str(item['place_area']) + '㎡',
      'plannedHouseholds': str(int(item['get_count']) + k * 10) + "户",
      'parkingLotRat': '共' + str(int(item['get_count']) * 50) + '个机动车位，车位配比为1：1',
      'greenRat': str(item['get_count'] * 2.5),
      'floorAreaRat': str(int(3.254 + k)),
      'mainLayout': 'A-' + str(int(item['get_count']) * 10 + 10),

      # 第四排
      'buildCom': builds[bk],
      'estateCom': esteComs[bk],
      'estateFee': str(bk + 1),
      'deliverDate': creat_time,
      'content': item['commission'] + item['extend'],
      'showIndex': str(0)
    }
    print('item==>'+picurl)
    addFangs(fangObj)



if __name__ == '__main__':
  sousuoLgb()
  # addFangs()
  # addFangs()
